package com.loan.market.util

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.loan.market.R
import com.loan.market.databinding.LayoutBottomSheetBinding

open class SheetItem(val id: String = "", val content: String = "")

fun Activity.showSheet(data: List<SheetItem>?, onClick: (sheetItem: SheetItem) -> Unit) {
    if (data.isNullOrEmpty()) return
    showSheet(data.map { it.content }) {
        onClick(data[it])
    }
}

fun Activity.showSheet(data: List<String>?, onClick: String.(position: Int) -> Unit) {
    if (data.isNullOrEmpty()) return
    val bottomSheetDialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
    val bottomBinding = LayoutBottomSheetBinding.inflate(layoutInflater)

    val adapter = object : BaseQuickAdapter<String, QuickViewHolder>() {
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: String?) {
            holder.setText(R.id.tv_name, item)
            holder.setGone(R.id.divider, position == itemCount - 1)
        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_bottom_sheet, parent)
        }
    }
    bottomBinding.rv.adapter = adapter
    adapter.setOnItemClickListener { _, view, position ->
        bottomSheetDialog.dismiss()
        adapter.getItem(position)?.onClick(position)
    }
    adapter.addAll(data)
    bottomSheetDialog.setContentView(bottomBinding.root)
    bottomSheetDialog.show()
}